import { useState, useRef } from 'react';
import { motion } from 'framer-motion';
import { toast } from 'sonner';
import { useCart } from '@/contexts/CartContext';
import { useLanguage } from '@/contexts/LanguageContext';
import { Link } from 'react-router-dom';
import { getImageUrl } from '@/lib/utils';

interface Product {
  id: number;
  nameKey: string;
  price: number;
  descriptionKey: string;
  image: string;
  categoryKey: string;
}

interface ProductCardProps {
  product: Product;
}

export default function ProductCard({ product }: ProductCardProps) {
  const { t } = useLanguage();
  const [isHovered, setIsHovered] = useState(false);
   
    const { addToCart } = useCart();
    const [animationTrigger, setAnimationTrigger] = useState(false);
    const productImageRef = useRef<HTMLImageElement>(null);
    
    // 处理添加到购物车并触发动画
    const handleAddToCart = () => {
      addToCart({
        id: product.id,
        nameKey: product.nameKey,
        price: product.price,
        image: product.image,
        quantity: 1
      });
      
      // 触发飞入购物车动画
      triggerAddToCartAnimation();
    };
    
    // 创建飞入购物车动画
    const triggerAddToCartAnimation = () => {
      if (!productImageRef.current) return;
      
      // 获取购物车图标位置
      const cartIcon = document.getElementById('cart-icon-container');
      if (!cartIcon) return;
      
      // 创建一个临时图片元素
      const flyingImage = document.createElement('img');
      flyingImage.src = product.image;
      flyingImage.alt = 'Product flying to cart';
      
      // 设置初始样式
      flyingImage.style.position = 'fixed';
      flyingImage.style.zIndex = '9999';
      flyingImage.style.width = '50px';
      flyingImage.style.height = '50px';
      flyingImage.style.objectFit = 'cover';
      flyingImage.style.borderRadius = '50%';
      flyingImage.style.boxShadow = '0 4px 8px rgba(0,0,0,0.2)';
      flyingImage.style.transition = 'all 1.2s cubic-bezier(0.2, 0.8, 0.2, 1)';
      
      // 获取产品图片位置
      const productRect = productImageRef.current.getBoundingClientRect();
      flyingImage.style.left = `${productRect.left + productRect.width / 2 - 25}px`;
      flyingImage.style.top = `${productRect.top + productRect.height / 2 - 25}px`;
      
      // 添加到文档
      document.body.appendChild(flyingImage);
      
      // 触发重排
      requestAnimationFrame(() => {
        // 获取购物车图标位置
        const cartRect = cartIcon.getBoundingClientRect();
        
        // 设置目标位置
        flyingImage.style.left = `${cartRect.left + cartRect.width / 2 - 25}px`;
        flyingImage.style.top = `${cartRect.top + cartRect.height / 2 - 25}px`;
        flyingImage.style.width = '30px';
        flyingImage.style.height = '30px';
        flyingImage.style.opacity = '0';
        
        // 动画结束后移除元素
        setTimeout(() => {
          document.body.removeChild(flyingImage);
          // 触发购物车图标的动画
          setAnimationTrigger(true);
          setTimeout(() => setAnimationTrigger(false), 100);
        }, 800);
      });
    };

  return (
    <motion.div
      className="group bg-white rounded-xl overflow-hidden shadow-md hover:shadow-xl transition-all duration-300 flex flex-col h-full"
      onMouseEnter={() => setIsHovered(true)}
      onMouseLeave={() => setIsHovered(false)}
      whileHover={{ y: -5 }}
      transition={{ duration: 0.3 }}
    >
       {/* Product Image with Link */}
      <div className="relative overflow-hidden aspect-square">
         <Link to={`/product/${product.id}`}>
                 <img 
               src={product.image} 
             alt={t(product.nameKey)}
             ref={productImageRef}
             className="w-full h-full object-cover transition-transform duration-500 group-hover:scale-110 cursor-pointer"
          />
        </Link>
        
        {/* Category Tag */}
        <div className="absolute top-3 left-3 bg-blue-100 text-blue-800 text-xs font-medium px-2.5 py-0.5 rounded-full">
          {t(product.categoryKey)}
        </div>
      </div>
      
       {/* Product Info */}
      <div className="p-4 flex-grow flex flex-col">
        <Link to={`/product/${product.id}`}>
          <h3 className="font-semibold text-lg text-gray-800 mb-1 line-clamp-1 hover:text-blue-600 transition-colors cursor-pointer">{t(product.nameKey)}</h3>
        </Link>
        <p className="text-gray-600 text-sm mb-3 line-clamp-2 flex-grow">{t(product.descriptionKey)}</p>
         <div className="flex justify-between items-center mt-auto">
           <button
             onClick={handleAddToCart}
             className="bg-blue-600 hover:bg-blue-700 text-white py-1.5 px-3 rounded-full transition-colors font-medium text-sm"
           >
             <i className="fa-solid fa-shopping-cart mr-1"></i>
             {t('addToCart')}
           </button>
        </div>
      </div>
    </motion.div>
  );
}